function padLeftZero(str) {
  return ('00' + str).substr(str.length);
}

function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    );
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + '';
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      );
    }
  }
  return fmt;
}
function formatDateMillisecond(millisecond) {
  let date = new Date(millisecond);
  return formatDate(date, 'yyyy-MM-dd hh:mm:ss');
}
function MathRand() {
  let Num = '';
  for (let i = 0; i < 6; i++) {
    Num += Math.floor(Math.random() * 10);
  }
  return Num;
}

function getSearch(keys, defaultVaule) {
  let hash = window.location.search || window.location.hash;
  let sValue = hash.substring(hash.indexOf('?') + 1);
  let sArr = sValue.split('&');
  for (let key in sArr) {
    let item = sArr[key];
    let iArr = item.split('=');
    if (iArr[0] === keys) {
      return iArr[1];
    }
  }
  return defaultVaule;
}

/**
 * 获取 blob
 * @param  {String} url 目标文件地址
 * @return {Promise}
 */
function getBlob(url) {
  return new Promise((resolve) => {
    const xhr = new XMLHttpRequest();

    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      }
    };

    xhr.send();
  });
}

/**
 * 保存
 * @param  {Blob} blob
 * @param  {String} filename 想要保存的文件名称
 */
function saveAs(blob, filename) {
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename);
  } else {
    const link = document.createElement('a');
    const body = document.querySelector('body');

    link.href = window.URL.createObjectURL(blob);
    link.download = filename;

    // fix Firefox
    link.style.display = 'none';
    body.appendChild(link);

    link.click();
    body.removeChild(link);

    window.URL.revokeObjectURL(link.href);
  }
}

/**
 * 下载
 * @param  {String} url 目标文件地址
 * @param  {String} filename 想要保存的文件名称
 */
function download(url, filename, callback) {
  getBlob(url).then((blob) => {
    saveAs(blob, filename);
    if (callback) {
      callback();
    }
  });
}

function getCookie(name) {
  let strcookie = document.cookie; //获取cookie字符串
  let arrcookie = strcookie.split('; '); //分割
  //遍历匹配
  for (let i = 0; i < arrcookie.length; i++) {
    let arr = arrcookie[i].split('=');
    if (arr[0] == name) {
      return arr[1];
    }
  }
  return '';
}

export default {
  formatDate: formatDate,
  formatDateMillisecond: formatDateMillisecond,
  getSearch: getSearch,
  MathRand: MathRand,
  download: download,
  getCookie: getCookie,
};
